/**
 * Created by HTWX on 2018/3/12.
 */
var express = require('express');
var router = express.Router();
var BaseModel = require('../models/base_model');
var baseModel = new BaseModel();
var Q = require('q');


function checktel(data){
   var deferred = Q.defer();
   var sql="select tel from yk_user where tel='" + data + "'";
    baseModel.findOneById(sql,function(ret){
        console.log(ret);
        deferred.resolve(ret);
    });
    return deferred.promise;
}

function addtel(data){
    var deferred = Q.defer();
    var tableName = 'yk_user';
    var rowInfo = {
        'tel':data
    };
    baseModel.insert(tableName,rowInfo,function(ret){
            console.log(ret);
            deferred.resolve(ret);
    });
    return deferred.promise;
}

router.post('/', function (req, res) {
    res.clearCookie('smscodes');
    res.cookie('ownuser',req.body.phone, {maxAge:100000*6000, path:'/', httpOnly:false});
    checktel(req.body.phone).then(function (result) {
        if(!result) {
            addtel(req.body.phone).done(function(ret){
                res.redirect('/');
            })
        }
        else {
            res.redirect('/');
        }
    });
});

module.exports = router;